##-*- coding: UTF-8 -*-
#coding=UTF-8
import cgi
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp

class Greeting(db.Model):
    author = db.StringProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)


class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write('<html><body>')

        greetings = db.GqlQuery("SELECT * "
                            "FROM Greeting "
                            "ORDER BY date DESC LIMIT 10")
        for greeting in greetings:
            if greeting.author:
                self.response.out.write(greeting.author+' wrote:')
            else:
                self.response.out.write('An anonymous person wrote:')
            
            self.response.out.write('<blockquote>%s</blockquote>' %cgi.escape(greeting.content))

        self.response.out.write("""
              <form action="/guestbook/CommitContent" method="post">
                <div>Your Name:<input name="author"></div>
                <div>msg for me:<textarea name="content" rows="3" cols="60"></textarea></div>
                <div><input type="submit" value="commit your massage!"></div>
              </form>
            </body>
          </html>""")


class Guestbook(webapp.RequestHandler):
    def post(self):
        greeting = Greeting()

#        if users.get_current_user():
#            greeting.author = users.get_current_user()
        greeting.author = self.request.get('author')
        greeting.content = self.request.get('content')
        greeting.put()
        self.redirect('/guestbook/')

application = webapp.WSGIApplication([
      ('/guestbook/', MainPage),
      ('/guestbook/CommitContent', Guestbook)
    ], debug=True)


def main():
    wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
    main()
